package com.kylin.java;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPTest1 {

    //客服端
    @Test
    public void client() throws IOException {
        //1.创建Socket对象，指明服务器的ip和端口号 本机ip
        InetAddress localHost = InetAddress.getLocalHost();//获取本机ip InetAddress对象
        InetAddress inet = InetAddress.getByName("192.168.1.1");//通过本机ip 获取InetAddress对象
        Socket socket = new Socket(localHost, 8899);
        //2.获取输出流，用于输出数据
        OutputStream os = socket.getOutputStream();
        //3.写出数据
        os.write("你好我是客户端".getBytes());

        //4.关闭资源
        os.close();
        socket.close();
    }

    //服务端
    @Test
    public void server() throws IOException {
        //1.创键SocketServer对象
        ServerSocket serverSocket = new ServerSocket(8899);
        //2.调用accept()表示接受客户端的socket
        Socket socket = serverSocket.accept();
        //3.获取输入流
        InputStream is = socket.getInputStream();
        //4.读取输入流中的数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            String str = new String(buffer, 0, len);
            System.out.print(str);
        }
        //5.关闭资源
        is.close();
        socket.close();
        serverSocket.close();
    }
}
